<template>
  <div class="app-container">

    <el-form :model="form" ref="form" label-width="100px" v-loading="formLoading" :rules="rules">
      <el-form-item label="用户名："  prop="userName" required>
        <el-input v-model="form.userName"></el-input>
      </el-form-item>
      <el-form-item label="密码：" required>
        <el-input v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item label="真实姓名：" prop="realName"   required>
        <el-input v-model="form.realName"></el-input>
      </el-form-item>
      <!-- <el-form-item label="年龄：">
        <el-input v-model="form.age"></el-input>
      </el-form-item> -->
      <el-form-item label="性别：">
        <el-select v-model="form.sex" placeholder="性别" clearable>
          <el-option v-for="item in sexEnum" :key="item.key" :value="item.key" :label="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出生日期：">
        <el-date-picker v-model="form.birthDay" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"/>
      </el-form-item>
      <el-form-item label="邮箱：" required  prop="email">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item label="手机号：" required prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <!-- <el-form-item label="邮箱密钥：">
        <el-input v-model="form.emailKey"></el-input>
      </el-form-item> -->
      <el-form-item label="企业名称：" required prop="companyId">
        <el-select
          v-model="form.companyId"
          placeholder="选择企业"
          clearable
          :disabled="userInfo.role !== 3"
          @change="handleCompanyChange">
          <el-option
            v-for="company in companyList"
            :key="company.id"
            :value="company.id"
            :label="company.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" required>
        <el-select v-model="form.status" placeholder="状态">
          <el-option v-for="item in statusEnum" :key="item.key" :value="item.key" :label="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters, mapState, mapActions } from 'vuex'
import userApi from '@/api/user'
import companyApi from '@/api/company'

export default {
  data () {
    return {
      form: {
        id: null,
        userName: '',
        password: '',
        realName: '',
        phone: '',
        role: 2,
        status: 1,
        age: '',
        sex: '',
        birthDay: null,
        email: null,
        emailKey: null,
        companyId: null,
        companyName: '',
        userInfo: ''
      },
      formLoading: false,
      companyList: [],
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: function (rule, value, callback) {
              if (
                /^\w{1,64}@[ a-z0-9\- ]{1,256}(\.[a-z]{2,6}){1,2}$/i.test(value) === false
              ) {
                callback(new Error('请输入正确的邮箱'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          {
            validator: function (rule, value, callback) {
              if (/^1[34578]\d{9}$/.test(value) === false) {
                callback(new Error('手机号格式错误'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        companyId: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ]
      }
    }
  },
  created () {
    this.getUserInfo()
    this.loadCompanies()
    let id = this.$route.query.id
    let _this = this
    if (id && parseInt(id) !== 0) {
      _this.formLoading = true
      userApi.selectUser(id).then(re => {
        _this.form = re.response
        _this.formLoading = false
      })
    }
  },
  methods: {

    getUserInfo() {
      this.userInfo = this.$store.state.user.userInfo
      if (this.userInfo.role !== 3) {
        this.form.companyName = this.userInfo.companyName
        this.form.companyId = this.userInfo.companyId
      }
    },

    loadCompanies() {
      companyApi.list().then(response => {
        if (response.code === 1) {  // Check if the API call was successful
          this.companyList = response.response  // Use response.response instead of response.data
        } else {
          this.$message.error('获取企业列表失败')
        }
      }).catch(error => {
        console.error('Error loading companies:', error)
        this.$message.error('获取企业列表失败')
      })
    },
    submitForm () {
      let _this = this
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.formLoading = true
          userApi.createUser(this.form).then(data => {
            if (data.code === 1) {
              _this.$message.success(data.message)
              _this.delCurrentView(_this).then(() => {
                _this.$router.push('/user/company/list')
              })
            } else {
              _this.$message.error(data.message)
              _this.formLoading = false
            }
          }).catch(e => {
            _this.formLoading = false
          })
        } else {
          return false
        }
      })
    },
    resetForm () {
      let lastId = this.form.id
      this.$refs['form'].resetFields()
      this.form = {
        id: null,
        userName: '',
        password: '',
        realName: '',
        role: 2,
        status: 1,
        age: '',
        sex: '',
        birthDay: null,
        phone: null,
        companyId: null,
        companyName: ''
      }
      this.form.id = lastId
    },
    handleCompanyChange(value) {
      const selectedCompany = this.companyList.find(company => company.id === value)
      if (selectedCompany) {
        this.form.companyName = selectedCompany.name
      } else {
        this.form.companyName = ''
      }
    },
    ...mapActions('tagsView', { delCurrentView: 'delCurrentView' })
  },
  computed: {
    ...mapGetters('enumItem', [
      'enumFormat'
    ]),
    ...mapState('enumItem', {
      sexEnum: state => state.user.sexEnum,
      roleEnum: state => state.user.roleEnum,
      statusEnum: state => state.user.statusEnum
    })
  }
}
</script>
